package cn.jett.domain.strategy.service.armory;

import cn.jett.domain.strategy.model.entity.StrategyAwardEntity;
import cn.jett.domain.strategy.model.entity.StrategyEntity;
import cn.jett.domain.strategy.model.entity.StrategyRuleEntity;
import cn.jett.domain.strategy.repository.IStrategyRepository;
import cn.jett.domain.strategy.service.rule.chain.factory.DefaultChainFactory;
import cn.jett.types.common.Constants;
import cn.jett.types.enums.ResponseCode;
import cn.jett.types.exception.AppException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.security.SecureRandom;
import java.util.*;

/**
 * @Author 战斗天使
 * @Description 策略装配库，负责 初始化策略计算
 * @Date 2024/6/14
 */
@Service
@Slf4j
public class StrategyArmoryDispatch implements IStrategyArmory,IStrategyDispatch{

    //策略仓储层
    @Resource
    private IStrategyRepository repository;

    /**
     * 抽奖概率装配（生成概率查找表存入redis）
     * @param strategyId
     */
    @Override
    public boolean assembleLotteryStrategy(Long strategyId) {
        //1.查询策略配置(根据策略id查询该策略id下的所有奖品id和奖品概率的集合)
        List<StrategyAwardEntity> strategyAwardEntities = repository.queryStrategyAwardList(strategyId);

        // 2 缓存奖品库存【用于decr扣减库存使用】
        for (StrategyAwardEntity strategyAward : strategyAwardEntities) {
            Integer awardId = strategyAward.getAwardId();
            Integer awardCount = strategyAward.getAwardCount();
            cacheStrategyAwardCount(strategyId, awardId, awardCount);
        }

        //redis装配概率表
        assembleLotteryStrategy(String.valueOf(strategyId), strategyAwardEntities);
        StrategyEntity strategyEntity = repository.queryStrategyEntityByStrategyId(strategyId);
        //该策略无配置规则
        if (null == strategyEntity.getRuleModels()){
            return true;
        }
        //该策略无配置权重规则则无需继续操作，装配完成
        if (!this.isRuleWeight(strategyEntity.getRuleModels())){
            return true;
        }
        // 权重策略配置（rule_weight）
        String ruleWeight = strategyEntity.getRuleWeight();
        //判断策略规则表中是否有对应规则
        StrategyRuleEntity strategyRuleEntity = repository.queryStrategyRule(strategyId,ruleWeight);
        if (null == strategyRuleEntity){
            throw new AppException(ResponseCode.STRATEGY_RULE_WEIGHT_IS_NULL.getCode(), ResponseCode.STRATEGY_RULE_WEIGHT_IS_NULL.getInfo());
        }
        //获取权重值的map
        Map<String, List<Integer>> ruleWeightValueMap = strategyRuleEntity.getWeightValue();
        //获取所有权重键
        Set<String> keys = ruleWeightValueMap.keySet();
        for (String key:keys) {
            List<Integer> ruleWeightValues = ruleWeightValueMap.get(key);
            ArrayList<StrategyAwardEntity> strategyAwardEntitiesClone = new ArrayList<>(strategyAwardEntities);
            //在策略奖品集合中删除当前规则中没有的奖品
            strategyAwardEntitiesClone.removeIf(entity->!ruleWeightValues.contains(entity.getAwardId()));
            assembleLotteryStrategy(String.valueOf(strategyId).concat("_").concat(key), strategyAwardEntitiesClone);
        }
        return true;
    }

    /**
     * 判断该策略是否包括权重规则
     * @param rules
     * @return
     */
    public boolean isRuleWeight(String rules){
        String[] splitRules = rules.split(Constants.SPLIT);
        for (String rule:splitRules) {
            if (DefaultChainFactory.LogicModel.RULE_WEIGHT.getCode().equals(rule)){
                return true;
            }
        }
        return false;
    }

    /**
     * 抽奖概略装配（生成概率查找表存入redis）
     * @param key
     * @param strategyAwardEntities
     */
    public void assembleLotteryStrategy(String key,List<StrategyAwardEntity> strategyAwardEntities){
        //1.获取最小概率值
        BigDecimal minAwardRate = strategyAwardEntities.stream()
                .map(StrategyAwardEntity::getAwardRate)
                .min(BigDecimal::compareTo)
                .orElse(BigDecimal.ZERO);
        //2.获取概率值总和
        BigDecimal totalAwardRate = strategyAwardEntities.stream()
                .map(StrategyAwardEntity::getAwardRate)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        //3.用概率值总和%最小概率值获取概率范围，百分位，千分位，万分位(向上取整）
        BigDecimal rateRange = totalAwardRate.divide(minAwardRate, 0, RoundingMode.CEILING);

        //4.生成概率表
        ArrayList<Integer> strategyAwardSearchRateTables = new ArrayList<>(rateRange.intValue());
        for (StrategyAwardEntity strategyAward:strategyAwardEntities) {
            Integer awardId = strategyAward.getAwardId();
            BigDecimal awardRate = strategyAward.getAwardRate();
            //计算每个奖品所需要的数组长度，循环填充
            for (int i = 0; i < rateRange.multiply(awardRate).setScale(0, RoundingMode.CEILING).intValue(); i++) {
                strategyAwardSearchRateTables.add(awardId);
            }
        }
        //5.乱序
        Collections.shuffle(strategyAwardSearchRateTables);
        //6.将概率表填充进哈希表
        HashMap<Integer, Integer> shuffleStrategyAwardSearchRateTables = new HashMap<>();
        for (int i = 0; i < strategyAwardSearchRateTables.size(); i++) {
            shuffleStrategyAwardSearchRateTables.put(i,strategyAwardSearchRateTables.get(i));
        }

        //7.将哈希表存储到redis
        repository.storeStrategyAwardSearchRateTables(key,shuffleStrategyAwardSearchRateTables.size(),shuffleStrategyAwardSearchRateTables);
    }

    /**
     * 根据策略id进行抽奖
     * @param strategyId
     * @return
     */
    @Override
    public Integer getRandomAwardId(Long strategyId) {
        //获取概率范围
        int rateRange = repository.getRateRange(strategyId);
        //产生随机值查找表结果
        return repository.getStrategyAwardAssemble(String.valueOf(strategyId), new SecureRandom().nextInt(rateRange));
    }

    /**
     * 根据策略id和权重值进行抽奖
     * @param strategyId
     * @param ruleWeightValue
     * @return
     */
    @Override
    public Integer getRandomAwardId(Long strategyId, String ruleWeightValue) {
        String key = String.valueOf(strategyId).concat("_").concat(ruleWeightValue);
        //获取概率范围
        int rateRange = repository.getRateRange(key);
        //产生随机值查找表结果
        return repository.getStrategyAwardAssemble(key, new SecureRandom().nextInt(rateRange));
    }

    /**
     * 缓存奖品库存到Redis
     *
     * @param strategyId 策略ID
     * @param awardId    奖品ID
     * @param awardCount 奖品库存
     */
    private void cacheStrategyAwardCount(Long strategyId, Integer awardId, Integer awardCount) {
        String cacheKey = Constants.RedisKey.STRATEGY_AWARD_COUNT_KEY + strategyId + Constants.UNDERLINE + awardId;
        repository.cacheStrategyAwardCount(cacheKey, awardCount);
    }

    /**
     * 库存扣减
     * @param strategyId
     * @param awardId
     * @return
     */
    @Override
    public Boolean subtractionAwardStock(Long strategyId, Integer awardId) {
        String cacheKey = Constants.RedisKey.STRATEGY_AWARD_COUNT_KEY + strategyId + Constants.UNDERLINE + awardId;
        return repository.subtractionAwardStock(cacheKey);
    }
}
